package com.vehicle.admin.web.common.shiro.token;

import com.vehicle.ucenter.api.entity.SysMenu;
import com.vehicle.ucenter.api.entity.SysRole;
import com.vehicle.ucenter.api.entity.SysUser;
import com.vehicle.ucenter.api.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by yantingbin on 2017/7/14.
 */
@Component
public class SampleRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser user = TokenManager.getToken();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        List<SysRole> roles = user.getRoles();
        List<SysMenu> menus = user.getMenus();

        info.setRoles(roles.stream().map(r -> r.getName()).collect(Collectors.toSet()));
        info.setStringPermissions(menus.stream().map(m -> m.getPermission()).collect(Collectors.toSet()));

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        ShiroToken token = (ShiroToken) authenticationToken;
        SysUser sysUser = sysUserService.login(token.getUsername());
        if (sysUser == null) {
            throw new AccountException("账号或密码不正确！！");
        } else if (!sysUser.getEnabled()) {
            throw new DisabledAccountException("账号已被禁用！！");
        } else {
            sysUser.setUpdateDate(new Date());
            sysUserService.updateInfo(sysUser);
        }
        return new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), sysUser.getLoginName());
    }

    public void clearCachedAuthorizationInfo(){
        PrincipalCollection principalCollection= SecurityUtils.getSubject().getPrincipals();
        SimplePrincipalCollection principals=new SimplePrincipalCollection(principalCollection,getName());
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection){
        SimplePrincipalCollection principals=new SimplePrincipalCollection(principalCollection,getName());
        super.clearCachedAuthorizationInfo(principals);
    }
}
